package org.vellos.halide.vm.Math;

import org.vellos.halide.parse.ExpressionNode;

public class BasicMath {

  public static String add(ExpressionNode en) throws NotANumberException {
    Double result = 0.0;

    for (Object o : en.getNodes().subList(1, en.getNodes().size())) {
      try {
        result += Double.parseDouble((String) o);
      } catch (Exception e) {
        throw new NotANumberException((String) o);
      }
    }

    if (result % 1 == 0) {
      return "" + result.intValue();
    }

    return result.toString();
  }

  public static String subtract(ExpressionNode en) throws NotANumberException {
    Double result = Double.parseDouble((String) en.getNodes().get(1));

    for (Object o : en.getNodes().subList(2, en.getNodes().size())) {
      try {
        result -= Double.parseDouble((String) o);
      } catch (Exception e) {
        throw new NotANumberException((String) o);
      }
    }

    if (result % 1 == 0) {
      return "" + result.intValue();
    }

    return result.toString();
  }

  public static String multiply(ExpressionNode en) throws NotANumberException {
    Double result = Double.parseDouble((String) en.getNodes().get(1));

    for (Object o : en.getNodes().subList(2, en.getNodes().size())) {
      try {
        result *= Double.parseDouble((String) o);
      } catch (Exception e) {
        throw new NotANumberException((String) o);
      }
    }

    if (result % 1 == 0) {
      return "" + result.intValue();
    }

    return result.toString();
  }

  public static String divide(ExpressionNode en) throws NotANumberException, DivisionByZeroException {
    Double result = Double.parseDouble((String) en.getNodes().get(1));

    for (Object o : en.getNodes().subList(2, en.getNodes().size())) {
      try {
        Double doubleVal = Double.parseDouble((String) o);
        if (doubleVal == 0) {
          throw new DivisionByZeroException();
        }
        result /= doubleVal;
      } catch (Exception e) {
        if (e instanceof DivisionByZeroException) {
          throw (DivisionByZeroException) e;
        } else {
          throw new NotANumberException((String) o);
        }
      }
    }

    if (result % 1 == 0) {
      return "" + result.intValue();
    }

    return result.toString();
  }
}
